package com.hmdp.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;

import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {



    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1 进行手机号格式检验
        if (RegexUtils.isPhoneInvalid(phone))
        {
            //2 手机号格式不正确，返回
            System.out.println("手机号格式不正确");
            return  Result.fail("手机号格式不正确，请重新输入");

        }
        //3 格式正确，生成验证码
         String s = RandomUtil.randomNumbers(6);
        /*//4 保存验证码到session
        session.setAttribute("code",s);*/
        // 4 保存到redis中 同时提供验证码的存活时间
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone,s,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //5 发送验证码 使用日志来模拟
        log.debug("该手机所发送的验证码为:"+s);
        // 返回结果
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //页面提供的手机号
        String phone =loginForm.getPhone();
        //页面提供的验证码
        String code =loginForm.getCode();
        //获取redis中缓存的验证码
        String cacheCode=stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY+phone);

        //1 ：检验手机号
        if (RegexUtils.isPhoneInvalid(phone))
        {
            //2 手机号格式不正确，返回
            System.out.println("手机号格式不正确");
            return  Result.fail("手机号格式不正确，请重新输入");

        }
        //3 校验验证码
         if(cacheCode==null||!cacheCode.equals(code))
         {
             return Result.fail("验证码错误，请重新输入");
         }

        //5 判断用户是否存在
         User user1 = query().eq("phone", phone).one();
            if(user1==null){
                //6 用户不存在，创建用户
                user1=createUser(phone);
            }
            //5 跟上边的实现一样
        /*LambdaQueryWrapper<User> l =new LambdaQueryWrapper<>();
            l.eq(User::getPhone,loginForm.getPhone());
        User one = userService.getOne(l);*/
        //7 保存用户到session中
        //7 保存用户信息到redis中
        //7.1 随机生成token来作为登录令牌
        String token = UUID.randomUUID().toString();
        //7.2  将得到的user1对象转换为userdto来存储在redis中
        UserDTO userDTO = BeanUtil.copyProperties(user1, UserDTO.class);
        //将该对象存储在hashmap中以便于存放在redis中
        Map<String,String> map =new HashMap<>();
        map.put("icon",userDTO.getIcon());
        map.put("id",String.valueOf(userDTO.getId()));
        map.put("nickName",userDTO.getNickName());
        //7.3 存储
        String tokenKey=RedisConstants.LOGIN_USER_KEY+token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,map);
        //7.4设置有效时间为30分钟
        stringRedisTemplate.expire(tokenKey,30,TimeUnit.MINUTES);

        return Result.ok(token);
    }

    private User createUser(String phone) {
        User u=new User();
        u.setPhone(phone);
        u.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(6));
        save(u);
        return u;
    }

    @Override
    public Result sign() {
         /*//获取登录用户
         Long userId = UserHolder.getUser().getId();
         //获取当前日期
         LocalDateTime nowTime = LocalDateTime.now();
         //拼接key
        String yyyyMM = nowTime.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key="sign:"+userId+yyyyMM;
        //获取今天是本月的第几天
        int dayOfMonth = nowTime.getDayOfMonth();
        //写入reids  set key offset i
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();*/
        //获取当前用户的id
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
         LocalDateTime now = LocalDateTime.now();
        String format = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        //拼接key
        String key="sign:"+userId+":"+format;
        int dayOfMonth = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }

    @Override
    public Result countSign() {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //获取当前日期
         LocalDateTime now = LocalDateTime.now();
         //拼接key
        String format = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key="sign:"+userId+format;
        //获取今天是第几天
        int dayOfMonth = now.getDayOfMonth();
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0)
        );
        if(result==null||result.isEmpty())
        {
            //没有签到结果
            return Result.ok(0);
        }
        Long num =result.get(0);
        if(num==null||num==0){
            return Result.ok(0);
        }
        //循环遍历
        int count = 0;
        while (true){
            //让这个数字与1做与运算，得到数字的最后一个bit位   //判读这个bit位是否为0
            if ((num & 1) == 0){
                //如果为0，说明未签到，结束
                break;
            }else {
                //如果不为0，说明已签到，计数器加1
                count++;
            }
            //把数字右移一位，抛弃最后一个bit位，继续下一个bit位
            num >>>= 1;
        }
        return Result.ok(count);
    }





}
